package com.smart.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.smart.dao.Page;
import com.smart.dao.PageRequest;
import com.smart.model.ApplyRecord;
import com.smart.model.Loan;
import com.smart.model.User;
import com.smart.util.StringUtil;

@Controller
public class ApplyRecordController extends BaseController{
	@RequestMapping(value = "admin/applyRecord/list")
	public String listApplyRecord(PageRequest pageRequest, Model model){
		Page<ApplyRecord> page = applyRecordService.findAll(pageRequest);
		model.addAttribute("page", page);
		return "admin/applyRecord/list";
	}
	
	@RequestMapping(value = "admin/applyRecord/edit", method=RequestMethod.GET)
	public String preEditApplyRecord(Long id, Model model) {
		if(id!=null){
			ApplyRecord applyRecord = applyRecordService.findOne(id);
			model.addAttribute("obj", applyRecord);
		}
		return "admin/applyRecord/edit";
	}
	
	@RequestMapping(value = "admin/applyRecord/edit", method=RequestMethod.POST)
	public String editApplyRecord(ApplyRecord form, Model model, RedirectAttributes ra) {
		applyRecordService.save(form);
		model.addAttribute("obj", form);
		setSuccessMsg(ra);
		return "redirect:edit?id=" + form.getId();
	}
	
	@RequestMapping(value = "admin/applyRecord/delete", method=RequestMethod.GET)
	public @ResponseBody String deleteApplyRecord(Long id) {
		applyRecordService.delete(id);
		return "OK";
	}
	@RequestMapping("apply")
	public @ResponseBody String apply(String uid,String loanId) {
		if(StringUtil.isNotEmpty(uid) && StringUtil.isNotEmpty(loanId)) {
			Long userId = Long.valueOf(uid);
			Long lId = Long.valueOf(loanId);
			User user = userService.findOne(userId);
			Loan loan = loanService.findOne(lId);
			if(user!=null && loan!=null) {
				ApplyRecord record = new ApplyRecord();
				record.setLoanId(lId);
				record.setUserId(userId);
				record.setNickName(user.getNickName());
				record.setMobile(user.getMobilePhone());
				record.setLoanName(loan.getName());
				applyRecordService.save(record);
				return "ok";
			}else {
				return "user not exist";
			}
		}
		return "ok";
	}
}
